/*
 * File: Toml.java
 * Author: Force Charlie
 * CreateTime: @2018.12
 * Copyright (C) 2018. GITEE.COM.All Rights Reserved.
 */

package svnserver.service;

import java.io.FileNotFoundException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;

import net.consensys.cava.toml.Toml;
import net.consensys.cava.toml.TomlParseResult;

public class TomlUtils {
    private static final Logger log = LoggerFactory.getLogger(TomlUtils.class);
    private TomlParseResult result;

    public TomlUtils() {
    }

    boolean ParseFile(@NotNull String file, boolean ignoreNotFound) {
        Path source = Paths.get(file);
        try {
            result = Toml.parse(source);
            if (result.hasErrors()) {
                return false;
            }
        } catch (FileNotFoundException | NoSuchFileException e) {
            if (!ignoreNotFound) {
                log.error("TomlUtils.ParseFile", e);
            }
            return false;
        } catch (Exception e) {
            log.error("TomlUtils.ParseFile", e);
            return false;
        }
        return true;
    }

    public String get(String key, String dev) {
        if (!result.contains(key) || !result.isString(key)) {
            return dev;
        }
        return result.getString(key);
    }

    public boolean get(String key, boolean dev) {
        if (!result.contains(key) || !result.isBoolean(key)) {
            return dev;
        }
        return result.getBoolean(key);
    }

    public long get(String key, long value) {
        if (!result.contains(key) || !result.isLong(key)) {
            return value;
        }
        return result.getLong(key);
    }

    public double get(String key, double value) {
        if (!result.contains(key) || !result.isDouble(key)) {
            return value;
        }
        return result.getDouble(key);
    }

    public long lookupSizeBytes(String key, long mb) {
        if (!result.contains(key)) {
            return mb * 1024 * 1024;
        }
        if (result.isDouble(key)) {
            long dmb = result.getDouble(key).longValue();
            return dmb * 1024 * 1024;
        }
        if (result.isLong(key)) {
            return result.getLong(key) * 1024 * 1024;
        }
        return mb * 1024 * 1024;
    }

}